package com.sail.gateway.config;

import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class DynamicRouteService {
    private final RouteDefinitionWriter routeDefinitionWriter;
    private final RouteDefinitionLocator routeDefinitionLocator;

    public DynamicRouteService(RouteDefinitionWriter routeDefinitionWriter,
                               RouteDefinitionLocator routeDefinitionLocator) {
        this.routeDefinitionWriter = routeDefinitionWriter;
        this.routeDefinitionLocator = routeDefinitionLocator;
    }

    @EventListener
    public void onEnvironmentChange(EnvironmentChangeEvent event) {
        if (event.getKeys().contains("spring.cloud.gateway.routes")) {
            routeDefinitionLocator.getRouteDefinitions()
                    .subscribe(routeDefinitions -> {
//                        routeDefinitionWriter.delete("*").subscribe();
//                        routeDefinitionWriter.save(routeDefinitions).subscribe();
                    });
        }
    }
}